package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"strings"
)

var num int = 0

func GetHtml(url string, i int) (result string, err error) {
	resp, err := http.Get(url)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	buf := make([]byte, 4096)
	for {
		read, err2 := resp.Body.Read(buf)
		if read == 0 {
			fmt.Println("第" + strconv.Itoa(i) + "页读取完毕...")
			break
		}
		if err2 != nil && err2 != io.EOF {
			err = err2
			return
		}

		result += string(buf[:read])
	}
	return
}

func getImg(img string) {
	path := "./" + strconv.Itoa(num) + ".png"
	file, err := os.Create(path)
	if err != nil {
		fmt.Println("Create err:", err)
	}
	defer file.Close()
	resp, err := http.Get(img)
	if err != nil {
		fmt.Println("http GET err:", err)
		return
	}
	defer resp.Body.Close()
	buf := make([]byte, 4096)
	for {
		read, err2 := resp.Body.Read(buf)
		if read == 0 {
			fmt.Println("第" + strconv.Itoa(num) + "个图片读取完毕...")
			break
		}
		if err2 != nil && err2 != io.EOF {
			err = err2
			return
		}
		file.Write(buf[:read])

	}

}

func pageGet(url string, i int) {
	result, err := GetHtml(url, i)
	if err != nil {
		fmt.Println("GEThtml err:", err)
		return
	}
	//<img src=""
	compile := regexp.MustCompile(`src="(?s:(.*?))"`)
	//compile := regexp.MustCompile(`<img src="(?s:(.*?))"`)
	submatch := compile.FindAllStringSubmatch(result, -1)

	for _, img := range submatch {
		nimg := "https:" + img[1]
		replace := strings.Replace(nimg, "_cp", "_bp", 1)
		getImg(replace)
		num++
	}
}

func work(start, end int) {
	for i := start; i <= end; i++ {
		//https://www.pixiv.net/ranking.php?mode=daily&date=20220604
		url := "https://anime-pictures.net/pictures/view_posts/" + strconv.Itoa(i-1) + "?lang=zh_CN"
		//url := "https://www.pixiv.net/ranking.php?mode=daily&date=2022060" + strconv.Itoa(i)
		pageGet(url, i)
	}

}

func main() {
	var start, end int
	start, _ = strconv.Atoi(os.Args[1])
	end, _ = strconv.Atoi(os.Args[2])

	work(start, end)
}
